package com.simple.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.simple.mapper.ocrmark.EsMarkMapper;
import com.simple.mapper.ocrmark.OcrQuestionMarkMapper;
import com.simple.mapper.ocrmark.YoudaoMapper;
import com.simple.mapper.ocrmark.YoudaoMarkMapper;
import com.simple.util.OCRYouDaoUtil;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class YoudaoMarkService {

    @Autowired
    private YoudaoMarkMapper youdaoMarkMapper;
    @Autowired
    private OcrQuestionMarkMapper ocrQuestionMarkMapper;

    @Value("${ocrmark.imgPath}")
    private String imgPath;

    @Value("${youdao.ocrquestionapi.id}")
    private String youdaoID;

    @Value("${youdao.ocrquestionapi.key}")
    private String youdaoKey;

    @Autowired
    YoudaoMapper youdaoMapper;


    public Map getOneImg(){
        Map map = new HashMap();
        String img = youdaoMarkMapper.getOneImg();
        if(img != null && !"".equals(img)) {
            youdaoMarkMapper.marking(img);
        }else{
            return null;
        }
        map.put("name",img);
        String filePath = imgPath + img;
        if(!new File(filePath).exists()){
            System.err.println(filePath+" 服务器文件不存在........................");
            return null;
        }
        byte[] bytes = getBytes(new File(filePath));
        org.apache.commons.codec.binary.Base64 base64 = new  org.apache.commons.codec.binary.Base64();
        String imgBase64 = base64.encodeToString(bytes);
        map.put("imgBase64","<img src=\"data:image/jpeg;base64," + imgBase64 + "\" width=\"800\" height=\"300\">");
        return map;
    }



    public void updateMark(Map map) {
        youdaoMarkMapper.updateMark(map);
    }



    public void initData() {
        List<Map<String,Object>> data = ocrQuestionMarkMapper.queryIsMarkNoSearch();
        List<String> imgs = new ArrayList<>();
        for(Map<String,Object> map : data){
            imgs.add((String)map.get("img_name"));
        }
        youdaoMarkMapper.insertBatch(imgs);
    }


    public void initDataSql() {
        youdaoMarkMapper.insertInit();
    }

    public void updateDealBatch(List<String> imgs) {
        youdaoMarkMapper.updateDealBatch(imgs);
    }

    public void updateDeal(List<String> imgs) {
        for(String img : imgs){
            youdaoMarkMapper.updateDeal(img);
        }

    }

    public static byte[] getBytes(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            // picture max size is 2MB
            ByteArrayOutputStream bos = new ByteArrayOutputStream(2000 * 1024);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }



    public Map getDealYoudao(){
        Map map = new HashMap();
        map.put("totalCount", youdaoMarkMapper.queryAllCount());
        map.put("isMarkCount",youdaoMarkMapper.queryIsMarkCount());
        map.put("noMarkCount",youdaoMarkMapper.queryNoMarkCount());
        return map;
    }


    public void  unlockMarking(){
        youdaoMarkMapper.unlockMarking();
    }


    public JSONObject youdaoQuestionByImageUp(String fileName) throws Exception {
        // fileName = "09389_15834E3566EE98FDFEE6481B81A5AB12.jpg";
        String json = YouDaoQuestion.ocrquestionapi(getLocalFileBase64(fileName),youdaoID,youdaoKey);
        JSONObject rs = null;
        if(null != json){
            JSONObject jsonObj = JSON.parseObject(json);
            rs  = new JSONObject();

            //"errorCode": "0"
            if("0".equals(jsonObj.getString("errorCode")) || jsonObj.get("data") != null){
                JSONObject data = jsonObj.getJSONObject("data");
                if(null != data){
                    JSONArray questions = data.getJSONArray("questions");
                    rs.put("errorCode","0");
                    JSONObject rsData  = new JSONObject();
                    JSONArray rsQs  = new JSONArray();
                    rsData.put("questions",rsQs);
                    rs.put("data",rsData);

                    if(null != questions && questions.size()>0){
                        //存入数据库
                        //youdao_id,answer,subject,analysis,type,content,knowledge,text,img_name
                        for(int i=0; i<questions.size(); i++){
                            JSONObject q  = questions.getJSONObject(i);
                            Map qs = new HashMap();
                            qs.put("text",data.getString("text"));
                            qs.put("img_name",fileName);
                            qs.put("youdao_id",q.getString("id"));
                            qs.put("answer",q.getString("answer"));
                            qs.put("subject",q.getString("subject"));
                            qs.put("analysis",q.getString("analysis"));
                            qs.put("type",q.getString("type"));
                            qs.put("content",q.getString("content"));
                            qs.put("knowledge",q.getString("knowledge"));
                            //数据库是否已存在
                            if(youdaoMapper.queryIsSearch(qs) == 0){
                                youdaoMapper.insertYoudaoQs(qs);
                            }
                            JSONObject rsc = new JSONObject();
                            rsc.put("content",q.getString("content"));
                            rsQs.add(rsc);
                        }
                    }
                }
            }else{
                return null;
            }
        }
        return rs;//JSONObject.parseObject(json);
    }


    public String getLocalFileBase64 (String fileName){
        String filePath = imgPath + fileName;
        String imageBase64 = getImageStr(new File(filePath));
        return imageBase64;
    }


    /**
     * 获得图片的Base64编码
     * @param imgFile
     * @return
     */
    private static String getImageStr(File imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(in != null) {
                try {
                    in.close();
                }
                catch(Exception e) {

                }
            }
        }
        // 对字节数组Base64编码
        return Base64.encode(data);
    }

}

